package com.hcinfos.gsoo.ui;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ListWheelAdapter;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.AddImgAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Area;
import com.hcinfos.gsoo.enity.ImageInfo;
import com.hcinfos.gsoo.enity.Type;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DataChangeCallback;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.util.CommonUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.ImageUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.view.StartTimeItemLayout;

public class AddShopActivity extends Activity implements OnClickListener,
		DataChangeCallback {

	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;

	private TextView add_pic;

	private EditText shopname_et;// 店名
	private EditText pinyin_et;// 拼音
	private EditText email_et;// 邮箱
	private LinearLayout area_ll;// 区域
	private LinearLayout address_ll;// 地址
	private LinearLayout type_ll;// 类型
	private EditText average_et;// 人评
	private TextView startTime;// 开始时间
	private TextView endTime;// 结束时间
	private EditText person_et;// 负责人
	private EditText tag_et;// 标签
	private EditText descr_et;// 描述
	private EditText area_et;
	private EditText address_et;
	private EditText type_et;
	private EditText phone_et;

	private Dialog startTimeDialog;
	private Dialog endTimeDialog;
	private LayoutInflater inflater;
	private RelativeLayout start_ll;
	private LinearLayout startTime_ll;
	private RelativeLayout endTime_rl;

	private String[] weeks = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
	private Button startTime_Ok;
	private Button endTime_Ok;

	private View addMenuView;
	private Button pai;
	private Button album;
	private Button cancel;
	private Gallery gallery;
	private AddImgAdapter galleryAdapter;
	private List<ImageInfo> galleryList;

	private final int GET_IMG_RESULT_CODE = 0x1120;
	private final int CAMERA_IMG_RESULT_CODE = GET_IMG_RESULT_CODE + 1;
	private final int LOOK_IMG_RESULT_CODE = GET_IMG_RESULT_CODE + 2;
	private final int GET_ADDRESS_RESULT_CODE = GET_IMG_RESULT_CODE + 3;// 获取地址
	private final int SUBMIT_INFO_SUCCESS = GET_IMG_RESULT_CODE + 4;
	private final int SUBMIT_FAIL = GET_IMG_RESULT_CODE + 5;
	private final int SUBMIT_IMG_SUCCESS = GET_IMG_RESULT_CODE + 6;
	private final int GET_AREA_RESULT_CODE = GET_IMG_RESULT_CODE + 7;
	private final int GET_TYPE_RESULT_CODE = GET_IMG_RESULT_CODE + 8;
	private final int SUBMIT_IMG_FAIL = GET_IMG_RESULT_CODE + 9;

	private ContentResolver resolver;
	private Bitmap addBitmap;
	private EditText address_content;
	private Button submit_button;

	private ImageView map_icon;

	private boolean isStartTimeEmpty = true;// 开始时间
	private boolean isEndTimeEmpty = true;// 结束时间

	private Dialog dialog;

	private SharePreferenceUtil util;
	private Activity activity;
	private final int ADDSHOP_RESULT_CODE = 0x9900;
	private Context context;
	private String email;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_addshop);
		activity = this;
		context = this;
		util = new SharePreferenceUtil(this, "setting");
		dialog = DialogUtil.createProgressDialog(this, "信息提交", "店铺信息提交中");

		initRes();
	}

	OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				return true;
			} else {
				return false;
			}
		}
	};

	private void initRes() {
		resolver = getContentResolver();
		galleryList = new ArrayList<ImageInfo>();
		gallery = (Gallery) findViewById(R.id.gallery);
		galleryAdapter = new AddImgAdapter(this, galleryList);
		galleryAdapter.setDataChangeCallback(this);
		gallery.setAdapter(galleryAdapter);
		addBitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.picturebackground_center_normal);
		ImageInfo info = new ImageInfo();
		info.setIndex(0);
		info.setBitmap(addBitmap);
		galleryList.add(info);
		gallery.setOnItemClickListener(galleryItemClickListener);
		inflater = getLayoutInflater();
		start_ll = (RelativeLayout) inflater.inflate(R.layout.starttime_dialog,
				null);
		startTime_ll = (LinearLayout) start_ll.findViewById(R.id.start_ll);

		for (int i = 0; i < weeks.length; i++) {
			StartTimeItemLayout layout = new StartTimeItemLayout(this);
			layout.setValue(weeks[i]);
			startTime_ll.addView(layout);
		}
		startTime_Ok = (Button) start_ll.findViewById(R.id.startTime_Ok);
		startTime_Ok.setOnClickListener(this);

		endTime_rl = (RelativeLayout) inflater.inflate(R.layout.endtime_dialog,
				null);
		endTime_Ok = (Button) endTime_rl.findViewById(R.id.endTime_Ok);
		endTime_Ok.setOnClickListener(this);

		addMenuView = inflater.inflate(R.layout.addpic, null);
		pai = (Button) addMenuView.findViewById(R.id.pai);
		pai.setOnClickListener(this);
		album = (Button) addMenuView.findViewById(R.id.album);
		album.setOnClickListener(this);
		cancel = (Button) addMenuView.findViewById(R.id.cancel);
		cancel.setOnClickListener(this);

		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("店铺收录");
		add_pic = (TextView) findViewById(R.id.add_pic);
		add_pic.setOnClickListener(this);

		shopname_et = (EditText) findViewById(R.id.shopname_et);
		shopname_et.addTextChangedListener(shopNameWatcher);
		pinyin_et = (EditText) findViewById(R.id.pinyin_et);
		email_et = (EditText) findViewById(R.id.email_et);
		email_et.setEnabled(false);
		area_ll = (LinearLayout) findViewById(R.id.area_ll);
		area_ll.setOnClickListener(this);
		address_ll = (LinearLayout) findViewById(R.id.address_ll);
		// address_ll.setOnClickListener(this);
		type_ll = (LinearLayout) findViewById(R.id.type_ll);
		type_ll.setOnClickListener(this);
		average_et = (EditText) findViewById(R.id.average_et);
		startTime = (TextView) findViewById(R.id.startTime);
		startTime.setOnClickListener(this);
		endTime = (TextView) findViewById(R.id.endTime);
		endTime.setOnClickListener(this);
		person_et = (EditText) findViewById(R.id.person_et);
		tag_et = (EditText) findViewById(R.id.tag_et);
		descr_et = (EditText) findViewById(R.id.descr_et);
		map_icon = (ImageView) findViewById(R.id.map_icon);
		map_icon.setOnClickListener(this);
		address_content = (EditText) findViewById(R.id.address_et);
		submit_button = (Button) findViewById(R.id.submit_button);
		submit_button.setOnClickListener(this);
		area_et = (EditText) findViewById(R.id.area_et);
		address_et = (EditText) findViewById(R.id.address_et);
		type_et = (EditText) findViewById(R.id.type_et);
		phone_et = (EditText) findViewById(R.id.phone_et);
		initTimeRes();

		user = (User) util.loadObject("user");
		if (user == null) {
			DialogUtil.createNoCancelDialog(AddShopActivity.this, "请先登陆,再提交!",
					new DialogCallBack() {

						@Override
						public void viewClick() {

						}

						@Override
						public void ok() {
							Intent intent = new Intent(AddShopActivity.this,
									LoginActivity.class);
							intent.putExtra("type", Constants.LOGIN_CODE);
							activity.startActivityForResult(intent,
									ADDSHOP_RESULT_CODE);

						}

						@Override
						public void init(Object obj) {

						}

						@Override
						public void cancel() {
							Intent intent = new Intent(AddShopActivity.this,
									MainTabActivity.class);
							startActivity(intent);
							finish();
						}
					}, "登陆", "取消", keylistener);
		} else {

			String email = user.getEmail();
			if (email != null) {
				email_et.setText(email);
			}
		}
	}

	TextWatcher shopNameWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			pinyin_et.setText(CommonUtil.getPinYin(s.toString()));
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	private User user;

	protected void onResume() {

		super.onResume();
	};

	private boolean doCheck() {
		String check = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
		Pattern regex = Pattern.compile(check);
		String email = email_et.getText().toString();
		Matcher matcher = regex.matcher(email);
		boolean isMatched = matcher.matches();
		if (shopname_et.getText().toString().length() == 0) {
			Toast.makeText(context, "店名不能为空", 500).show();
			return false;
		}
		if (area_et.getText().toString().length() == 0) {
			Toast.makeText(context, "所属区域不能为空", 500).show();
			return false;
		}
		if (address_et.getText().toString().length() == 0) {
			Toast.makeText(context, "详细地址不能为空", 500).show();
			return false;
		}
		if (type_et.getText().toString().length() == 0) {
			Toast.makeText(context, "所属类型未选择", 500).show();
			return false;
		}
		if (average_et.getText().toString().length() == 0) {
			Toast.makeText(context, "人均消费未填", 500).show();
			return false;
		}
		if (average_et.getText().toString().startsWith("0")) {
			Toast.makeText(context, "价格不能以0开始呃", 500).show();
			return false;
		}

		if (average_et.getText().toString().length() > 5) {
			Toast.makeText(context, "请认真填写价格哦!", 500).show();
			return false;
		}

		if (tag_et.getText().toString().length() == 0) {
			Toast.makeText(context, "未填标签", 500).show();
			return false;
		}
		if (descr_et.getText().toString().length() == 0) {
			Toast.makeText(context, "未填描述信息", 500).show();
			return false;
		}
		if (phone_et.getText().toString().length() == 0) {
			Toast.makeText(context, "电话不能为空!", 500).show();
			return false;

		}
		if (!isPhoneNumberValid(phone_et.getText().toString())) {

			Toast.makeText(context, "电话格式不对!", 500).show();
			return false;
		}
		return true;
	}

	public boolean isPhoneNumberValid(String phoneNumber) {
		boolean isValid = false;
		String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}d{1}-?d{8}$)|"
				+ "(^0[3-9] {1}d{2}-?d{7,8}$)|"
				+ "(^0[1,2]{1}d{1}-?d{8}-(d{1,4})$)|"
				+ "(^0[3-9]{1}d{2}-? d{7,8}-(d{1,4})$))";
		CharSequence inputStr = phoneNumber;
		Pattern pattern = Pattern.compile(expression);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	private List<String> hours;
	private List<String> mins;

	private String startTimeStr;
	private String endTimeStr;

	private void initTimeRes() {
		final WheelView hour = (WheelView) endTime_rl.findViewById(R.id.hour);
		final WheelView minute = (WheelView) endTime_rl
				.findViewById(R.id.minute);
		final WheelView end_hour = (WheelView) endTime_rl
				.findViewById(R.id.hour_end);
		final WheelView end_minute = (WheelView) endTime_rl
				.findViewById(R.id.minute_end);
		OnWheelChangedListener listener = new OnWheelChangedListener() {
			public void onChanged(WheelView wheel, int oldValue, int newValue) {

				startTimeStr = hours.get(hour.getCurrentItem()) + ":"
						+ mins.get(minute.getCurrentItem());
				endTimeStr = hours.get(end_hour.getCurrentItem()) + ":"
						+ mins.get(end_minute.getCurrentItem());

			}
		};

		hour.setInterpolator(new AnticipateOvershootInterpolator());
		minute.setInterpolator(new AnticipateOvershootInterpolator());
		end_hour.setInterpolator(new AnticipateOvershootInterpolator());
		end_minute.setInterpolator(new AnticipateOvershootInterpolator());
		hours = new ArrayList<String>();
		for (int i = 0; i < 24; i++) {
			if (i < 10) {
				hours.add("0" + i);
			} else {
				hours.add(i + "");
			}
		}
		Calendar calendar = Calendar.getInstance();
		int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
		hour.setViewAdapter(new DateListAdapter(this, hours, 0));
		hour.setCurrentItem(currentHour);
		hour.addChangingListener(listener);

		end_hour.setViewAdapter(new DateListAdapter(this, hours, 0));
		end_hour.setCurrentItem(currentHour);
		end_hour.addChangingListener(listener);

		mins = new ArrayList<String>();
		for (int i = 0; i < 60; i++) {
			if (i < 10) {
				mins.add("0" + i);
			} else {
				mins.add(i + "");
			}
		}
		int min = calendar.get(Calendar.MINUTE);
		minute.setViewAdapter(new DateListAdapter(this, mins, 0));
		minute.setCurrentItem(min);
		minute.addChangingListener(listener);

		end_minute.setViewAdapter(new DateListAdapter(this, mins, 0));
		end_minute.setCurrentItem(min);
		end_minute.addChangingListener(listener);

		startTimeStr = hours.get(hour.getCurrentItem()) + ":"
				+ mins.get(minute.getCurrentItem());
		endTimeStr = hours.get(end_hour.getCurrentItem()) + ":"
				+ mins.get(end_minute.getCurrentItem());
	}

	private class DateListAdapter extends ListWheelAdapter<String> {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public DateListAdapter(Context context, List<String> items, int current) {
			super(context, items);
			this.currentValue = current;
			setTextSize(16);
		}

		@Override
		protected void configureTextView(TextView view) {
			super.configureTextView(view);
			if (currentItem == currentValue) {
				// view.setTextColor(0xFF0000F0);
			}
			view.setTypeface(Typeface.DEFAULT);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}

	private PopupWindow menuWindow;
	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.add_pic:
			if (menuWindow == null) {
				menuWindow = getResultWindow();
			}
			menuWindow.showAtLocation(
					AddShopActivity.this.findViewById(R.id.main),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.left_ib:
			finish();
			break;
		case R.id.startTime:

			if (startTimeDialog == null) {
				startTimeDialog = new Dialog(this, R.style.QuitDialog);
				startTimeDialog.setContentView(start_ll);
			}
			Window dialogWindow = startTimeDialog.getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			dialogWindow.setGravity(Gravity.CENTER);
			lp.width = (int) (230 * Common.PROPORTION); // 宽度
			lp.height = (int) (250 * Common.PROPORTION); // 高度
			dialogWindow.setAttributes(lp);
			startTimeDialog.show();
			break;
		case R.id.endTime:
			if (endTimeDialog == null) {
				endTimeDialog = new Dialog(this, R.style.QuitDialog);
				endTimeDialog.setContentView(endTime_rl);
			}
			Window endWidow = endTimeDialog.getWindow();
			WindowManager.LayoutParams endLp = endWidow.getAttributes();
			endWidow.setGravity(Gravity.CENTER);
			endLp.width = (int) (230 * Common.PROPORTION); // 宽度
			endLp.height = (int) (300 * Common.PROPORTION); // 高度
			endWidow.setAttributes(endLp);
			endTimeDialog.show();
			break;
		case R.id.map_icon:
			intent = new Intent(this, AddressActivity.class);
			startActivityForResult(intent, GET_ADDRESS_RESULT_CODE);
			break;
		case R.id.type_ll:
			intent = new Intent(this, MoreTypeActivity.class);
			intent.putExtra("code", 1);
			startActivityForResult(intent, GET_TYPE_RESULT_CODE);
			break;
		case R.id.area_ll:
			intent = new Intent(this, MoreAreaActivity.class);
			startActivityForResult(intent, GET_AREA_RESULT_CODE);
			break;
		case R.id.startTime_Ok:
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < startTime_ll.getChildCount(); i++) {
				StartTimeItemLayout layout = (StartTimeItemLayout) startTime_ll
						.getChildAt(i);
				if (layout.isCheckValue()) {
					LogUtil.d("wxf", layout.getValue());
					sb.append(layout.getValue() + ",");
				}
			}
			startTime.setText(sb.toString());
			startTimeDialog.dismiss();
			break;
		case R.id.endTime_Ok:
			shopHours = startTime.getText() + "开始:" + startTimeStr + "结束:"
					+ endTimeStr;
			endTime.setText("开始:" + startTimeStr + "结束:" + endTimeStr);
			endTimeDialog.dismiss();
			break;
		case R.id.pai:
			menuWindow.dismiss();
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, CAMERA_IMG_RESULT_CODE);
			break;
		case R.id.cancel:
			menuWindow.dismiss();
			break;
		case R.id.album:
			menuWindow.dismiss();
			if (galleryList.size() > 5) {
				Toast.makeText(this, "一次最多可上传5张图片", 500).show();
				return;
			}
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			intent.setType("image/*");
			startActivityForResult(intent, GET_IMG_RESULT_CODE);
			break;
		case R.id.submit_button:

			if (doCheck()) {
				if (galleryList.size() <= 1) {
					Toast.makeText(this, "请选择上传店铺的图片", 500).show();
					return;
				}
				if (dialog != null)
					dialog.show();
				doSubmitInfo();
			}
			break;

		}
	}

	private void uploadImg() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				InputStream[] files = null;
				String[] fileNames = null;
				if (galleryList.size() <= 1)
					return;
				files = new InputStream[galleryList.size() - 1];
				fileNames = new String[galleryList.size()];
				for (int i = 1; i < galleryList.size(); i++) {
					LogUtil.d("wxf", "size:" + galleryList.size());
					ImageInfo info = galleryList.get(i);
					Bitmap bitmap = BitmapFactory.decodeFile(info.getPath());
					LogUtil.d("wxf", "path:" + info.getPath());
					files[i - 1] = new ByteArrayInputStream(
							CommonUtil.bitmap2Bytes(bitmap));
					fileNames[i - 1] = info.getName();

				}
				if (files.length == 0) {
					LogUtil.d("wxf", "null....");
					return;
				}
				String result = HttpClientUtil.uploadImg(context, null, files,
						fileNames, Urls.UPLOAD_IMG + "suppId=" + shopId);
				try {
					if (result != null) {

						JSONObject obj = new JSONObject(result);
						String message = obj.getString("message");
						int state = obj.getInt("state");
						if (state == 200) {
							Message msg = handler.obtainMessage();
							msg.what = SUBMIT_IMG_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = SUBMIT_IMG_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}
					} else {
						Message msg = handler.obtainMessage();
						msg.what = SUBMIT_IMG_FAIL;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = SUBMIT_FAIL;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	private String lat;
	private String lng;

	private String shopId;
	private String shopHours;
	private String areaid;
	private String typeid;

	private void doSubmitInfo() {
		final String suppName = shopname_et.getText().toString();
		final String suppNamepy = pinyin_et.getText().toString();
		final String emailStr = email_et.getText().toString();
		final String areaId = areaid;
		final String addressStr = address_et.getText().toString();
		final String latStr = lat;
		final String lngStr = lng;
		final String typeId = typeid;
		final String suppPerson = person_et.getText().toString();
		final String telPhone = phone_et.getText().toString();
		final String consumptionPer = average_et.getText().toString();
		final String supInfo = descr_et.getText().toString();
		final String tag = tag_et.getText().toString();
		new Thread(new Runnable() {

			@Override
			public void run() {

				Map<String, String> map = new HashMap<String, String>();
				map.put("supp.userId", user.getId());
				map.put("supp.suppName", suppName);
				map.put("supp.suppNamepy", suppNamepy);
				if (emailStr.length() != 0) {
					map.put("supp.email", emailStr);
				}
				map.put("supp.areaId", areaId);
				map.put("supp.addr", addressStr);
				map.put("supp.lon", lngStr);
				map.put("supp.lat", latStr);
				map.put("supp.typeId", typeId);
				map.put("supp.suppPerson", suppPerson);
				map.put("supp.telPhone", telPhone);
				map.put("supp.shopHours", shopHours);
				map.put("supp.consumptionPer", consumptionPer);
				map.put("supp.supInfo", supInfo);
				map.put("supp.tag", tag);
				try {
					String result = HttpClientUtil.postFromWebByHttp(
							AddShopActivity.this, Urls.ADD_SHOPINFO, map);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = SUBMIT_FAIL;
						handler.sendMessage(msg);
					} else {
						JSONObject obj = new JSONObject(result);
						String message = obj.getString("message");
						int state = obj.getInt("state");
						if (state == 200) {
							shopId = obj.getJSONObject("data").getString("id");
							Message msg = handler.obtainMessage();
							msg.what = SUBMIT_INFO_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = SUBMIT_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}
					}
					LogUtil.d("wxf", "result:" + result);

				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = SUBMIT_FAIL;
					handler.sendMessage(msg);
					LogUtil.d("wxf", e.toString());
					e.printStackTrace();
				}
			}
		}).start();
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}

	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 480, 800);
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case SUBMIT_INFO_SUCCESS:
				uploadImg();
				break;
			case SUBMIT_IMG_FAIL:
				if (dialog != null)
					dialog.dismiss();
				Toast.makeText(AddShopActivity.this, "上传图片失败,检查图片是否存在", 500)
						.show();
				break;
			case SUBMIT_FAIL:
				if (dialog != null)
					dialog.dismiss();
				if (msg.obj != null) {
					Toast.makeText(AddShopActivity.this, msg.obj.toString(),
							500).show();
				} else {
					Toast.makeText(AddShopActivity.this, "提交失败", 500).show();
				}
				break;
			case SUBMIT_IMG_SUCCESS:
				if (dialog != null)
					dialog.dismiss();
				// Intent intent = new Intent(AddShopActivity.this,
				// HomeActivity.class);
				// startActivity(intent);
				Toast.makeText(AddShopActivity.this, "提交成功", 500).show();
				finish();
				break;
			}
		};

	};

	public PopupWindow getResultWindow() {
		final PopupWindow resultWindow = new PopupWindow();
		// 设置按钮监听
		// 设置SelectPicPopupWindow的View
		resultWindow.setContentView(addMenuView);
		// 设置SelectPicPopupWindow弹出窗体的宽
		resultWindow.setWidth(LayoutParams.FILL_PARENT);
		// 设置SelectPicPopupWindow弹出窗体的高
		resultWindow.setHeight(LayoutParams.FILL_PARENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		resultWindow.setFocusable(true);
		// 设置SelectPicPopupWindow弹出窗体动画效果
		resultWindow.setAnimationStyle(R.style.AnimBottom);
		// 实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(Color.argb(125, 0, 0, 0));
		// 设置SelectPicPopupWindow弹出窗体的背景
		resultWindow.setBackgroundDrawable(dw);
		resultWindow.update();
		// mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
		addMenuView.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				int height = addMenuView.findViewById(R.id.pop_rl).getTop();
				int y = (int) event.getY();
				if (event.getAction() == MotionEvent.ACTION_UP) {
					if (y < height) {
						resultWindow.dismiss();
					}
				}
				return true;
			}
		});
		return resultWindow;
	}

	private OnItemClickListener galleryItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			if (position == 0) {
				menuWindow.showAtLocation(
						AddShopActivity.this.findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			} else {
				galleryAdapter.setPosition(position);
				galleryAdapter.notifyDataSetChanged();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case GET_IMG_RESULT_CODE:
			if (resultCode == Activity.RESULT_OK) {
				gallery.setVisibility(View.VISIBLE);
				add_pic.setVisibility(View.GONE);
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(data.getData(),
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				String newPath = CommonUtil.pngToJpgFromPath(picturePath);
				if (newPath == null) {
					Toast.makeText(this, "图片添加失败", 500).show();
					return;
				}
				ImageInfo info = new ImageInfo();
				info.setPath(newPath);
				info.setName(System.currentTimeMillis() + ".jpg");
				LogUtil.d("wxf", "picturePath" + picturePath);
				galleryList.add(info);
				galleryAdapter.setDataChange(galleryList);
			}
			break;
		case CAMERA_IMG_RESULT_CODE:
			if (resultCode == Activity.RESULT_OK) {
				gallery.setVisibility(View.VISIBLE);
				Uri uri = data.getData();
				Bitmap newbitmap = null;
				Bitmap bitmap = null;
				String imgPath = null;
				if (uri != null) {
					Cursor cursor = getContentResolver().query(uri, null, null,
							null, null);
					cursor.moveToFirst();
					imgPath = cursor.getString(1); // 图片文件路径
					cursor.close();
					if (imgPath != null) {
						bitmap = (Bitmap) data.getExtras().get("data");
						newbitmap = ImageUtil.rotaingImageView(90, bitmap);
					}
				} else {
					Bundle extras = data.getExtras();
					bitmap = (Bitmap) extras.get("data");
					newbitmap = bitmap;
					imgPath = CommonUtil.getSDPath() + "/"
							+ System.currentTimeMillis() + ".jpg";
				}
				if (imgPath == null) {
					Toast.makeText(context, "获取图片失败", 500).show();
					return;
				}
				File file = new File(imgPath);
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(file);
					newbitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
					fos.flush();
					fos.close();
					if (newbitmap != null && !newbitmap.isRecycled()) {
						newbitmap.recycle();
					}
					if (bitmap != null && !bitmap.isRecycled()) {
						bitmap.recycle();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				ImageInfo info = new ImageInfo();
				info.setPath(imgPath);
				info.setName(System.currentTimeMillis() + ".jpg");
				LogUtil.d("wxf", "info:" + info);
				galleryList.add(info);
				galleryAdapter.setDataChange(galleryList);

			}
			break;
		case GET_ADDRESS_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				String addressData = data.getStringExtra("address");
				lat = data.getStringExtra("lat");
				lng = data.getStringExtra("lng");
				LogUtil.d("wxf", "lat:" + lat);
				if (addressData != null) {
					address_content.setText(addressData);
				}
			}
			break;
		case ADDSHOP_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				String emailStr = util.loadStringSharedPreference("email");
				email_et.setText(emailStr);
			}
			break;
		case GET_AREA_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				Area area = (Area) data.getSerializableExtra("area");
				if (area == null)
					return;
				area_et.setText(area.getAreaName());
				areaid = area.getId();
			}
		case GET_TYPE_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				Type type = (Type) data.getSerializableExtra("type");
				if (type == null)
					return;
				type_et.setText(type.getTypeName());
				typeid = type.getId();
				LogUtil.d("wxf", "type_et:" + type.getTypeName());
			}
			break;
		}

	}

	@Override
	public void dataChange(List<?> list) {

		galleryList = (List<ImageInfo>) list;
		if (galleryList.size() == 1) {
			gallery.setVisibility(View.GONE);
			add_pic.setVisibility(View.VISIBLE);
		} else {
			gallery.setVisibility(View.VISIBLE);
			add_pic.setVisibility(View.GONE);
		}
	}

}
